package com.shengqin.controller.api;

import com.shengqin.common.pojo.CommonResult;
import com.shengqin.config.CommonException;
import com.shengqin.entity.*;
import com.shengqin.mapper.PlanMapper;
import com.shengqin.pojo.plan.PlanQueryParam;
import com.shengqin.pojo.plan.summary.ChartDataModel;
import com.shengqin.pojo.plan.summary.SummaryTotalProcessModel;
import com.shengqin.pojo.school.TreeModel;
import com.shengqin.pojo.summary.SummaryQueryParam;
import com.shengqin.service.*;
import com.shengqin.utils.GradeUtil;
import io.swagger.v3.oas.annotations.Operation;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

import static com.shengqin.utils.BmiUtil.buildLevel;

@RestController
@RequestMapping("/api/datav/")
public class DataViewController {

    @Resource
    private ISummaryResultService summaryResultService;
    @Resource
    private PlanMapper planMapper;
    @Resource
    private IPlanRelationClassesService planRelationClassesService;
    @Resource
    private ISchoolService schoolService;
    @Resource
    private IClassesService classesService;
    @Resource
    private IPlanService planService;

    @Operation(summary = "查询计划列表 根据学校ID 查询分组")
    @PostMapping("queryData")
    public CommonResult<Map<String, Object>> queryData(@RequestBody SummaryQueryParam queryParam) {
        if(queryParam.getPlanId() == null){
            if (!StringUtils.hasLength(queryParam.getCode())) {
                throw new CommonException("计划数据不正确，请重新确认");
            }
            Plan plan = planService.getByCode(queryParam.getCode());
            queryParam.setPlanId(plan.getId());
        }
        return CommonResult.data(summaryResultService.queryData(queryParam));
    }

    @PostMapping("summaryData")
    public CommonResult<Object> summaryData(@RequestBody PlanQueryParam planQueryParam) {
        if(planQueryParam.getPlanId() == null){
            if (!StringUtils.hasLength(planQueryParam.getCode())) {
                throw new CommonException("计划数据不正确，请重新确认");
            }
            Plan plan = planService.getByCode(planQueryParam.getCode());
            planQueryParam.setPlanId(plan.getId());
        }
        List<SummaryResult> summaryResultList = summaryResultService.listByPlanId(planQueryParam);
        List<ChartDataModel> bmiLevelList = new ArrayList<>();
        Map<String, Long> bmiLevelMap = new HashMap<>();
        summaryResultList.forEach(summaryResult -> {
            buildLevel(summaryResult, bmiLevelMap);
        });
        bmiLevelMap.forEach((key, value) -> {
            ChartDataModel chartDataModel = new ChartDataModel();
            chartDataModel.setName(key);
            chartDataModel.setValue(value);
            bmiLevelList.add(chartDataModel);
        });
        SummaryQueryParam queryParam = new SummaryQueryParam();
        queryParam.setPlanId(planQueryParam.getPlanId());
        SummaryTotalProcessModel processModel = planMapper.querySummaryDataForHealthPlan(queryParam);
        processModel.setBmiLevelData(bmiLevelList);
        return CommonResult.data(processModel);
    }

    @PostMapping("getSchoolList")
    public CommonResult<List<School>> getSchoolList(@RequestBody PlanQueryParam planQueryParam) {
        if(planQueryParam.getPlanId() == null){
            if (!StringUtils.hasLength(planQueryParam.getCode())) {
                throw new CommonException("计划数据不正确，请重新确认");
            }
            Plan plan = planService.getByCode(planQueryParam.getCode());
            planQueryParam.setPlanId(plan.getId());
        }
        List<PlanRelationClasses> schoolList = planRelationClassesService.listByPlanId(planQueryParam.getPlanId());
        if (CollectionUtils.isEmpty(schoolList)) {
            return CommonResult.data(new ArrayList<>());
        }
        Set<Integer> schoolIds = new HashSet<>();
        schoolList.forEach(planRelationClasses -> schoolIds.add(planRelationClasses.getShcoolId()));
        return CommonResult.data(schoolService.listByIds(schoolIds));
    }

    @PostMapping("getGradeClassesList")
    public CommonResult<List<TreeModel>> getGradeClassesList(@RequestBody PlanQueryParam planQueryParam) {
        if(planQueryParam.getPlanId() == null){
            if (!StringUtils.hasLength(planQueryParam.getCode())) {
                throw new CommonException("计划数据不正确，请重新确认");
            }
            Plan plan = planService.getByCode(planQueryParam.getCode());
            planQueryParam.setPlanId(plan.getId());
        }
        List<PlanRelationClasses> planRelationClassesList = planRelationClassesService.listByPlanIdAndSchoolId(planQueryParam.getPlanId(), planQueryParam.getSchoolId());

        Set<Integer> classesIds = new HashSet<>();
        planRelationClassesList.forEach(planRelationClasses -> {
            classesIds.add(planRelationClasses.getClassesId());
        });

        List<Classes> classesList = classesService.listByIds(classesIds);
        Map<Integer, List<Classes>> gradeClassesMap = classesList.stream().collect(Collectors.groupingBy(Classes::getGradeId));
        Map<Integer, String> gradeIdMap = new HashMap<>();
        List<TreeModel> gradeTreeModelList = new ArrayList<>();
        classesList.forEach(classes -> {
            if (!gradeIdMap.containsKey(classes.getGradeId())) {
                TreeModel gradeTreeModel = new TreeModel();
                gradeTreeModel.setName(GradeUtil.getGradeName(classes.getGradeId()));
                gradeTreeModel.setId(classes.getGradeId().toString());
                List<Classes> gradeClasses = gradeClassesMap.getOrDefault(classes.getGradeId(), new ArrayList<>());
                List<TreeModel> classesTreeModelList = new ArrayList<>();
                gradeClasses.forEach(gradeClass -> {
                    TreeModel classTreeModel = new TreeModel();
                    classTreeModel.setName(gradeClass.getName());
                    classTreeModel.setCode(gradeClass.getCode());
                    classTreeModel.setId(gradeClass.getId().toString());
                    classesTreeModelList.add(classTreeModel);
                });
                gradeTreeModel.setChildren(classesTreeModelList);
                gradeTreeModelList.add(gradeTreeModel);
                gradeIdMap.put(classes.getGradeId(), "");
            }
        });


        return CommonResult.data(gradeTreeModelList);
    }

}
